package com.qianli.user.facade.impl.auth;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.exception.enums.BasicErrorCodeEnum;
import com.fqgj.xjd.user.client.UserService;
import com.fqgj.xjd.user.client.enums.FrozenCodeEnum;
import com.fqgj.xjd.user.dao.UserAuthFirstRiskDao;
import com.fqgj.xjd.user.dao.UserAuthFirstRiskHistoryDao;
import com.fqgj.xjd.user.entity.UserAuthFirstRiskEntity;
import com.fqgj.xjd.user.entity.UserAuthFirstRiskHistoryEntity;
import com.qianli.user.application.UserAuthApplication;
import com.qianli.user.enums.CreditAuthTypeEnum;
import com.qianli.user.enums.UserAuthEnum;
import com.qianli.user.enums.UserAuthStatusEnum;
import com.qianli.user.facade.auth.UserAuthServiceFacade;
import com.qianli.user.facade.base.UserBaseInfoServiceFacade;
import com.qianli.user.ro.UserStateCode;
import com.qianli.user.ro.auth.*;
import com.qianli.user.ro.query.UserBaseQueryRO;
import com.qianli.user.service.UserAuthService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * name:用户认证信息
 * auth:ting.li@qianli-inc.com
 * date:2018/1/2 21:08
 * version: v1.0.0
 **/
@Service("userAuthServiceFacade")
public class UserAuthServiceFacadeImpl implements UserAuthServiceFacade{

    private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseInfoServiceFacade.class);

    @Autowired
    private UserAuthApplication userAuthApplication;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private UserAuthFirstRiskDao userAuthFirstRiskDao;
    @Autowired
    private UserAuthFirstRiskHistoryDao userAuthFirstRiskHistoryDao;
    @Autowired
    private UserService userService;
    /**
     * 取消认证
     * @param cancelAuth
     * @return
     */
    @Override
    public Response<Boolean> cancelAuth(UserCancelAuthRO cancelAuth) {
        if(null == cancelAuth){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == cancelAuth.getUserCode()){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param userCode can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == cancelAuth.getAuthType()){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param authType can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == CreditAuthTypeEnum.getEnumByType(cancelAuth.getAuthType())){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param can authType ILLEGAL");
            return Response.error(UserStateCode.ILLEGAL_PARAMS,"Parameter can not be empty");
        }
        Response<Boolean> response = userAuthApplication.cancelAuth(cancelAuth);
        return response;
    }

    /**
     * 人脸识别信审
     * @param userAuthFace
     * @return
     */
    @Override
    public Response<Boolean> auditAuthFaceRecognition(UserAuthFaceRO userAuthFace) {
        if(null == userAuthFace){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == userAuthFace.getUserCode()){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param userCode can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == userAuthFace.getFaceFailReasonTypeEnum()){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param faceFailReasonTypeEnum can not be null");
            return Response.error(UserStateCode.PARAMETER_LACK,"Parameter can not be empty");
        }
        if(null == userAuthFace.getPassed()){
            LOGGER.info("UserAuthServiceFacade.cancelAuth param can passed ILLEGAL");
            return Response.error(UserStateCode.ILLEGAL_PARAMS,"Parameter can not be empty");
        }
        Response<Boolean> response = userAuthApplication.auditAuthFaceRecognition(userAuthFace);
        return response;
    }

    @Override
    public Response<Boolean> updateUserAuthStatus(UserAuthRO userAuthRO) {
        if(userAuthRO == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"userAuthRO can not be empty");
        }
        if(userAuthRO.getUserAuthEnum() == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"UserAuthEnum can not be empty");
        }
        if(userAuthRO.getUserAuthStatusEnum() == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"UserAuthStatusEnum can not be empty");
        }
        Boolean result = userAuthService.updateUserAuthStatus(userAuthRO.getUserCode(), userAuthRO.getUserAuthStatusEnum(), userAuthRO.getUserAuthEnum());
        return Response.ok().putData(result);
    }

    @Override
    public Response<UserAuthStatusRO> queryUserAuthStatus(UserBaseQueryRO queryRO) {
        if(queryRO == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"userCode can not be empty");
        }
        UserAuthStatusRO userAuthStatusRO = userAuthService.getUserAuthStatus(queryRO.getUserCode());
        return Response.ok().putData(userAuthStatusRO);
    }

    @Override
    public Response<Boolean> pushFirstRoundRisk(UserPushRiskRequest userPushRiskRequest) {
        if(userPushRiskRequest == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"userPushRiskRequest can not be empty");
        }
        if(StringUtils.isBlank(userPushRiskRequest.getPushNo())
                || StringUtils.isBlank(userPushRiskRequest.getAppCode())){
            return Response.error(UserStateCode.PARAMETER_LACK,"param can not be empty");
        }
        UserAuthStatusRO userAuthStatus = userAuthService.getUserAuthStatus(userPushRiskRequest.getUserCode());
        if(userAuthStatus.getFirstRoundRiskStatus() != UserAuthStatusEnum.INIT.getCode() && userAuthStatus.getFirstRoundRiskStatus() != UserAuthStatusEnum.FAIL.getCode()){
            return Response.ok().putData(true);
        }


        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> firstRoundRiskCallBack(UserPushRiskCallbackRequest userPushRiskRequest) {
        LOGGER.info("============ 第一轮风控通过回调状态，userPushRiskRequest:{} ==========", JSONObject.toJSONString(userPushRiskRequest));
        if(userPushRiskRequest == null || StringUtils.isBlank(userPushRiskRequest.getPushNo()) || userPushRiskRequest.getRiskStatus() == null){
            return Response.error(BasicErrorCodeEnum.PARAM_VALID_ERROR, "param invalid");
        }
        if(UserAuthStatusEnum.getByCode(userPushRiskRequest.getRiskStatus()) == null){
            return Response.error(UserStateCode.PARAMETER_LACK,"riskStatus invalid");
        }
        UserAuthFirstRiskEntity userAuthFirstRiskEntity = userAuthFirstRiskDao.getByPushNo(userPushRiskRequest.getPushNo());
        if(userAuthFirstRiskEntity == null){
            return Response.error(UserStateCode.PARAMETER_LACK, "risk record not exist");
        }
        userAuthFirstRiskEntity.setRiskStatus(userPushRiskRequest.getRiskStatus());
        userAuthFirstRiskEntity.setRiskResult(userPushRiskRequest.getRiskResult());
        userAuthFirstRiskDao.updateByPrimaryKey(userAuthFirstRiskEntity);

        UserAuthFirstRiskHistoryEntity userAuthFirstRiskHistoryEntity = new UserAuthFirstRiskHistoryEntity();
        BeanUtils.copyProperties(userAuthFirstRiskEntity, userAuthFirstRiskHistoryEntity);
        userAuthFirstRiskHistoryEntity.setCreateDate(new Date());
        userAuthFirstRiskHistoryDao.insert(userAuthFirstRiskHistoryEntity);
        UserAuthStatusEnum userAuthStatus = UserAuthStatusEnum.SUCCESS;
        if(userPushRiskRequest.getRiskStatus() == UserAuthStatusEnum.REJECT.getCode()){
            userService.frozenUser(userAuthFirstRiskEntity.getUserCode(), FrozenCodeEnum.FIRST_RISK_FROZEN);
            userAuthStatus = UserAuthStatusEnum.REJECT;
        }
        if(userPushRiskRequest.getRiskStatus() == UserAuthStatusEnum.SUCCESS.getCode()){
            userAuthStatus = UserAuthStatusEnum.SUCCESS;
        }
        userAuthService.updateUserAuthStatus(userAuthFirstRiskEntity.getUserCode(), userAuthStatus, UserAuthEnum.FIRST_RISK_STATUS);

        return Response.ok().putData(true);
    }

    @Override
    public Response<UserAuthFirstRiskRO> getUserAuthFirstRisk(String riskNo) {
        if(StringUtils.isEmpty(riskNo)){
            return Response.error(BasicErrorCodeEnum.PARAM_VALID_ERROR, "riskNo cannot be empty");
        }
        UserAuthFirstRiskEntity userAuthFirstRiskEntity = userAuthFirstRiskDao.getByPushNo(riskNo);
        UserAuthFirstRiskRO userAuthFirstRiskRO = null;
        if(userAuthFirstRiskEntity != null){
            userAuthFirstRiskRO = new UserAuthFirstRiskRO();
            BeanUtils.copyProperties(userAuthFirstRiskEntity, userAuthFirstRiskRO);
        }
        return Response.ok().putData(userAuthFirstRiskRO);
    }

    @Override
    public Response<UserAuthFirstRiskRO> getUserAuthFirstRiskByUserCode(String userCode) {
        UserAuthFirstRiskEntity userAuthFirstRiskEntity = userAuthFirstRiskDao.getByUserCode(userCode);
        UserAuthFirstRiskRO userAuthFirstRiskRO = null;
        if(userAuthFirstRiskEntity != null){
            userAuthFirstRiskRO  = new UserAuthFirstRiskRO();
            BeanUtils.copyProperties(userAuthFirstRiskEntity, userAuthFirstRiskRO);
        }
        return Response.ok().putData(userAuthFirstRiskRO);
    }
}
